from pymongo import MongoClient
from configs.dbConfig import MONGOURL

client = MongoClient(MONGOURL)


def insertOne(db, collection, row, update=False, update_tag=True):
    if not update:
        if '_id' in row:
            res = client[db][collection].find_one({'_id': row['_id']})
            if res:
                return False
        client[db][collection].insert_one(row)
        return True
    else:
        older_row = client[db][collection].find_one({'_id': row['_id']})
        if older_row:
            if row.get('created_at'):
                del row['created_at']
            if row.get('created_at_date'):
                del row['created_at_date']
            older_row.update(row)
            client[db][collection].update_one({'_id': older_row.get('_id')}, {'$set': older_row}, upsert=False)
            return update_tag
        else:
            client[db][collection].insert_one(row)
            return True


def delOne(db, collection, condition):
    client[db][collection].delete_one(condition)


def query(db, collection, condition=None):
    if condition is None:
        condition = {}
    return client[db][collection].find(condition)


def query_one(db, collection, condition=None):
    if condition is None:
        condition = {}
    return client[db][collection].find_one(condition)

# 最后返回字典
def find_live_url(db, collection, live_names):
    hls_urls = {}
    for live_name in live_names:
        result = client[db][collection].find_one({'team': live_name})
        if result is not None and 'hls_url' in result:
            hls_urls[live_name] = result['hls_url']
    return hls_urls


# def insertOne_qianchaunAPI(db, collection, row, update=False, update_tag=True):
#     res = client[db][collection].find_one({'awemeShowId': 'Kans_SkinCare'})
#     if not res:
#         client[db][collection].insert_one(row)
#         return True
#     else:
#         if res['startTime'] == row['startTime']:
#             res['cost'] = row['cost']
#             res['gmv'] = row['gmv']
#             client[db][collection].update_one({'_id': res.get('_id')}, {'$set': res}, upsert=False)
#             return update_tag
#         else:
#             client[db][collection].delete_one({'awemeShowId': 'Kans_SkinCare'})
#             client[db][collection].insert_one(row)
#             return True



def insertOne_qianchaunAPI(db, collection, row, awemeShowId, update=False, update_tag=True):
    res = list(client[db][collection].find({'awemeShowId': awemeShowId}).sort('gmv'))

    # 如果row【startTime】与任意其他条数据的startTime不一样，则删除{'awemeShowId': awemeShowId}下的所有数据
    if any(r['startTime'] != row['startTime'] for r in res):
        client[db][collection].delete_many({'awemeShowId': awemeShowId})
        client[db][collection].insert_one(row)
        return True
    else:
        # 如果{'awemeShowId': awemeShowId}的数据没有超过10个，则继续加入
        if len(res) < 10:
            client[db][collection].insert_one(row)
            return True
        # 如果等于或者超过10个，则删除gmv最少的整条数据，增加此条数据
        else:
            min_gmv_data = res[0]  # 因为我们已经按照gmv排序，所以第一条数据是gmv最小的
            client[db][collection].delete_one({'_id': min_gmv_data.get('_id')})
            client[db][collection].insert_one(row)
            return True


def findAll_qianchaunAPI(db, collection, awemeShowId):
    # 获取{'awemeShowId': awemeShowId}的所有数据
    res = list(client[db][collection].find({'awemeShowId': awemeShowId}))

    # 提取cost和gmv字段，并按照cost从小到大排序
    cost_gmv_list = sorted([(r['cost'], r['gmv']) for r in res], key=lambda x: x[0])
    
    return cost_gmv_list

def findLast_qianchaunAPI(db, collection, condition=None):
    if condition is None:
        condition = {}
    cursor = client[db][collection].find(condition).sort('cost', -1).limit(1)
    return next(cursor, None)

def updata_deck(db,collection,comment_id,action):
    # 选择数据库
    db = client[db]
    
    # 选择集合
    redbook_actions_collection = db[collection]
    # 构建过滤条件
    filter_criteria = {
        'action': action,
        'comment_id': comment_id
    }
    # 构建更新操作
    update_operation = {'$set': {'double_deck': 1}}
    # 执行更新操作
    redbook_actions_collection.update_many(filter_criteria, update_operation)
if __name__ == '__main__':
    updata_deck('data_works', 'redbook_actions', '67ce9685000000001903573f','make_comment')
